package com.zhipu.hydration.utils;

import android.os.Looper;

import com.blankj.utilcode.util.LogUtils;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

public class HookLooper {
    private static final String TAG = "Suyf";

    public static void hook() {
        Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw); // 将出错的栈信息输出到 printWriter 中
            try {
                sw.close();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            pw.close();
            LogUtils.d("\n崩溃\n", "Thread: " + t.getName() + "\r\nErrorMessage: " + e.getMessage() + "\r\nStackTrace: " + sw.toString());
            if (Looper.myLooper() != Looper.getMainLooper()) {
                return;

            }
            while (true) {
                try {
                    LogUtils.d("Looper.loop===before");
                    if (Looper.myLooper() != null && Looper.myLooper() == Looper.getMainLooper()) {
                        Looper.loop();
                    } else {
                        break;
                    }
                    LogUtils.d("Looper.loop===after");
                } catch (Exception exception) {
                    LogUtils.d("Looper.loop===error: " + e.getMessage());
                }
            }
        });
    }
}
